package cn.genmer.test.security.concurrent;

import org.junit.Test;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;

/**
 * @program: securitydeomo
 * @description:
 * @author: Genmer
 * @create: 2022-04-22 21:35
 **/
@RestController
@RequestMapping("/test")
public class ConcurrentController {
    // 阻塞队列
    LinkedBlockingQueue<Request> queue = new LinkedBlockingQueue<>(1000);

    @GetMapping("/query")
    public Map<String, Object> query() throws ExecutionException, InterruptedException {
        CompletableFuture<Map<String, Object>> future = new CompletableFuture<>();
        Request request = new Request();
        request.setSerialNo(UUID.randomUUID().randomUUID().toString());
        request.setFuture(future);
        request.setPrimaryId("000");

        queue.add(request);

        TransferQueue<Character> queue2 = new LinkedTransferQueue<>();

        return future.get();


    }

    @Test
    public void divideTest(){
        System.out.println(Double.parseDouble(divide(750.3, 3200D)));

        Double a = 2.33;
        Double b = 2.33;
        System.out.println(a+b);

    }

    private static String divide(Double str1,Double str2) {
        try {
            if(str1==null||str1==0||str2==null||str2==0){
                return "0";
            }
            return new BigDecimal(str1).divide(new BigDecimal(str2),2, BigDecimal.ROUND_HALF_UP).toPlainString();
        }catch (Exception e){
            e.printStackTrace();
            return "0";
        }
    }

    @PostConstruct
    public void task(){
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(1);
        threadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                int size = queue.size();
                if (size == 0){
                    return;
                }
                // 组装参数
                List<Map<String, Object>> params = new ArrayList<>();
                // 与前端的对接
                List<Request> requests = new ArrayList<>();

                for (int i=0; i<size; i++){
                    Request request = queue.poll();
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("serialNo", request.getSerialNo());
                    map.put("primaryId", request.getPrimaryId());
                    params.add(map);
                    requests.add(request);
                }
                System.out.println("此次处理的数据量为： " + size);
                // 调用批量接口
            }
        }, 100, 10, TimeUnit.MILLISECONDS);
    }
}
